package com.atguigu.callable;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * ClassName: CallableDemo
 * Package: com.atguigu.callable
 * Description:
 *
 * @author: fu-wang
 * @create: 2024/10/29 20:56
 * version: 1.0
 */
public class CallableDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        new Thread(new MyRunnableThread(),"run").start();

        FutureTask<Integer> task = new FutureTask<>(new MyCallableThread());
        new Thread(task,"call").start();

        //task线程打断
//        Thread.sleep(1000);
//        task.cancel(true);
//        boolean cancelled = task.isCancelled();
//        System.out.println("cancelled = " + cancelled);

        //等待子线程执行完毕
        while (!task.isDone()){
            Thread.sleep(100);
            System.out.println("wait...");
        }

        //获取结果
        System.out.println("子线程结果" +task.get());
        System.out.println(Thread.currentThread().getName()+"\t"+"over");
    }
}
class MyCallableThread implements Callable<Integer>{

    @Override
    public Integer call() throws Exception {
        int i;
        for (i = 0; i < 10; i++) {
            Thread.sleep(300);
            System.out.println(Thread.currentThread().getName()+"执行了"+i);
        }
        return i;
    }
}
class MyRunnableThread implements Runnable{

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"Runnable");
    }
}
